package com.mooc.lib_network.interceptor

import com.mooc.lib_network.MD5Utils
import okhttp3.*
import okio.Buffer
import org.json.JSONObject

class SignInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val builder : Request.Builder = chain.request().newBuilder()
        val oldBody = chain.request().body()
        var buff = Buffer()
        oldBody!!.writeTo(buff)
        var oldJsonStr = buff.toString()
        buff.close()
        //{"key1":"value1"}
        //去除请求json对象中最外层{}，把key value 等所有内容+tamboo进行MD5加密
        //加密完成的字符串转小写
        //{"uName":"zxy","uPwd":"123456","time":"asdasd"}
        oldJsonStr = oldJsonStr.substring(oldJsonStr.indexOf("{"),oldJsonStr.lastIndexOf("}")+1)
        var job = JSONObject(oldJsonStr)
        var it = job.keys()
        var sb = StringBuffer()
        while (it.hasNext()){
            sb.append(job.getString(it.next()))
        }
        //{"key1":"value1","sign":"signStr"}
        var signStr = MD5Utils.createSign(sb.toString())
        job.put("sign",signStr)
        val body = RequestBody.create(MediaType.parse("application/json"),job.toString())
        builder.post(body)
        val request = builder.build()
        return chain.proceed(request)
    }
}